package com.example.bannerdemo;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.ui.PlayerView;

import java.util.List;

public class VideoPagerAdapter extends PagerAdapter {

    private final Context context;
    private final List<String> videoUrls;

    public VideoPagerAdapter(Context context, List<String> videoUrls) {
        this.context = context;
        this.videoUrls = videoUrls;
    }

    @Override
    public int getCount() {
        return videoUrls.size();
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        PlayerView playerView = new PlayerView(context);
        ExoPlayer player = new SimpleExoPlayer.Builder(context).build();

        String videoUrl = videoUrls.get(position);
        MediaItem mediaItem = MediaItem.fromUri(videoUrl);
        player.setMediaItem(mediaItem);
        player.prepare();
        player.setPlayWhenReady(true);

        playerView.setPlayer(player);
        playerView.setLayoutParams(new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
        ));

        container.addView(playerView);
        playerView.setTag(player);

        return playerView;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
        PlayerView playerView = (PlayerView) object;
        ExoPlayer player = (ExoPlayer) playerView.getTag();
        if (player != null) {
            player.release();
        }
        container.removeView(playerView);
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }
}
